var count = [];
var flag = true;
var projects = null;
$(function() {

    $("#mymap").height(document.documentElement.clientHeight);
    $("#mymap").width(document.body.clientWidth);
    /*MarkerClusterer.prototype._redraw = function () {

    	this._clearLastClusters();
    	this._createClusters();

    	var map=this._map;
    	for(var i=0,cluster;cluster=this._clusters[i];i++){//遍历所有的聚合点对象
    	    cluster._clusterMarker.onclick=function(){//在每个聚合点对象的视图对象上绑定事件
    	        //这样就可以为每一个聚合点绑定点击事件了
    	    	alert(123);
    	    }
    	}
    	}*/
    getProjectlist();
    
    //$("#mymap").children("div:eq(0)").children("div:eq(1)").children("div:eq(1)").children("div").live("mouseover",function(){//不可使用
    $("#mymap>div:eq(0)>div:eq(1)>div:eq(1)>div").on("mouseover",function(){
    	var index = $("#mymap div div:eq(1) div:eq(1) div").index(this);
		    	if(flag){
		    		var content = "<div  class='mytips' style='position:relative;left:-50px;top:-60px;width:300px;overflow:visible;line-height:20px;height:20px;'><span style='background:rgba(0,0,0,0.6);padding:12px 7px;color:white;font-size:12px;border-radius:3px;'>"+projects[index].name+"</span></div>";
		    		$(this).append(content);
		    	}
				
	});
	$("#mymap>div:eq(0)>div:eq(1)>div:eq(1)>div").on("mouseout",function(){
		  $(".mytips").remove();
	});
    
});

function getProjectlist(employeeId) {
    if(employeeId) {
        var employeeIds = employeeId;
    } else {
        var employeeIds = '';
    }
    publicAjax('common/listProjectStation', {
//		employeeId: '075C4091-D28C-4076-88BA-54E0629988D4'
    }, onSucc);

    function onSucc(data) {
    	projects =  data.data;
        projectsGlo = projects;
        initMap(projects);
        //loadtips(projects);
        // markerClusterer = new BMapLib.MarkerClusterer(map, {markers:markers});
        // window.frames["measuremanage"].window.pid = '1';
    }
}

var opts = {
    width : 250,     // 信息窗口宽度
    height: 80,     // 信息窗口高度
    title : "信息窗口" , // 信息窗口标题
    enableMessage:true//设置允许信息窗发送短息
}

var map;

var projectsGlo;

function initMap(dataList){
	count = [];
    // 百度地图API功能
    // 创建Map实例
    map = new BMap.Map("mymap");
    // 初始化地图,设置中心点坐标和地图级别
    map.centerAndZoom(new BMap.Point(116.331398,39.897445), 6);
    //添加地图类型控件
    map.addControl(new BMap.MapTypeControl({
        mapTypes:[
            BMAP_NORMAL_MAP,
            BMAP_HYBRID_MAP
        ]}));
    // 设置地图显示的城市 此项是必须设置的
    map.setCurrentCity("北京");
    //开启鼠标滚轮缩放
    map.enableScrollWheelZoom(true);
    
    var markerClusterer = null;
    //循环打点以及聚合
    if(dataList != null && typeof(dataList)!="undefined"){
    	
        for (var i = 0; i < dataList.length; i++) {
            var project = dataList[i];
            var markers = [];
            
            //循环工点
            var stations = dataList[i].child;
            if(typeof(stations)!="undefined" && stations != null && stations.length >0){
            	
                for( var j=0;j<stations.length;j++){
                    var station = stations[j];
                    //获取坐标
                    var coodinates = station.gpsCoOrdinates;
                    var lat = "";
                    var lon = "";
                    if(typeof(coodinates)!="undefined" && coodinates!=""){
                        lat = Number(coodinates.split(",")[1])+j/100000;
                        lon = Number(coodinates.split(",")[0])+j/100000;
                    }else{
                        continue;
                    }
                    var pt = new BMap.Point(lon, lat);
                    var marker = new BMap.Marker(pt);

                    map.addOverlay(marker);
                    // marker.addEventListener("click",attribute);
                    var content = station.name+";"+station.stationId+";"+station.projectId+";"+station.type+";"+project.name;
                    addClickHandler(content,marker);

                    markers.push(marker);
                }
                markerClusterer = new BMapLib.MarkerClusterer(map, {markers:markers});
                markerClusterer.setMinClusterSize(1);
                markerClusterer.setMaxZoom(6);
                count.push(markerClusterer.getClusters());
                //console.info(markerClusterer._clusters.length);
                /*for(var i=0,cluster;cluster=markerClusterer._clusters[i];i++){//遍历所有的聚合点对象
            	    cluster._clusterMarker.onmourseover=function(){//在每个聚合点对象的视图对象上绑定事件
            	        //这样就可以为每一个聚合点绑定点击事件了
            	    	alert(123);
            	    }
            	}*/
            }
        }
        
    }
 
    var panToLocation;
    var max;
    var first;

    //判断如果只有一个项目，那么就定位到该项目第一个工点
    if(dataList.length == 1){
        var projectTemp = dataList[0];
        for(var i=0;i<projectTemp.child.length;i++){
            if(typeof(projectTemp.child[i].gpsCoOrdinates) != 'undefined' && projectTemp.child[i].gpsCoOrdinates != ''){
                var new_point = new BMap.Point(projectTemp.child[i].gpsCoOrdinates.split(",")[0],projectTemp.child[i].gpsCoOrdinates.split(",")[1]);
                map.centerAndZoom(new_point,6);
                break;
            }
        }
    }else{
        map.centerAndZoom(new BMap.Point(116.331398,39.897445), 6);
    }
}
	
//标记marker，显示infowindow
function addMarker(point){
  var marker = new BMap.Marker(point, {
        icon: new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
            scale: 10,
            strokeWeight: 1,
            strokeColor: 'white',
            fillColor: 'red',
            fillOpacity: 0.99
        })
    });  

    var info = [
        "<div class='infotip'>",
            "<div class='circle'><span style='background-color:blue'>",
            60 ,
            "</span></div>",
            "<div class='msg'><span class='title'>人数：</span>"+ 10 + "<br/><span class='title'>提示：</span>" + 'this is a test' +"</div><span class='arrows'></span>" ,
        "</div>",
    ].join('');

    var infoWindow = new BMap.InfoWindow(info, {
        maxWidth: 100,
        maxHeight: 50
    });

    marker.addEventListener("click", function(){          
        map.openInfoWindow(infoWindow,point); //开启信息窗口
    });
    map.addOverlay(marker);
    return marker;
}

function addClickHandler(content,marker){
    marker.addEventListener("click",function(e){
        var temps = content.split(";");
        var type = temps[3];
        var stationId = temps[1];
        var sideMenu ;
        var liForOpen;
        var projectName = temps[4];
        //设置项目
        $('select[name="xiangmu"]',parent.document).val(temps[2]);
        window.parent.form.render('select');
        //设置工点
        for(var k=0;k<projectsGlo.length;k++){
            if(projectsGlo[k].projectId == temps[2]){
                $('select[name="gongdian"]',parent.document).html("");
                var stations = projectsGlo[k].child;
                for(var a=0;a<stations.length;a++){
                    var option1 = $("<option>").val(stations[a].stationId).text(stations[a].name).attr('type',stations[a].type);
                    $('select[name="gongdian"]',parent.document).append(option1);
                }
            }
        }
        $('select[name="gongdian"]',parent.document).val(temps[1]);
        window.parent.form.render('select');


        window.parent.window.parentId = stationId;
        publicAjax('menu/queryMenuByStation', {
            stationId: stationId
        }, function(data) {
            $(".side-menu",parent.document).html("<li class='menu-header'>操作菜单</li>");
            if(data.data && data.data.length > 0) window.parent.initMenu(data.data, $(".side-menu",parent.document));
            $(".side-menu > li",parent.document).addClass("menu-item");
            /!*获取菜单icon随机色*!/
            getMathColor();
            $(".side-menu > li a",parent.document).each(function(index){
                var alarmHref = "";
                switch(type){
                    case "1":
                        alarmHref = "/curve/alarm.html";
                        break;
                    case "2":
                        alarmHref = "/pier/alarm.html";
                        break;
                    case "3":
                        alarmHref = "/jikeng/alarm.html";
                        break;
                }


                var $this = $(this);
                if( typeof($this.attr("href"))!="undefined" && $this.attr("href").indexOf(alarmHref)>-1){
                    liForOpen = $this;
                    var animationSpeed = 300;
                    //var liForOpen = $(this);
                    var name = liForOpen.find('span').text();
                    var checkElement = liForOpen.next(); //这个函数只返回后面那个紧邻的同辈元素
                    store.set('optType',liForOpen.attr("data-option"));
                    if(liForOpen.attr("data-id")){
                        $(".img_right_icon").attr('src', 'common/images/arrow_right.png');
                        $(".side-menu .menu-item a>.img_right_icon").css('margin-top', '6px')
                    }else{
                        $(".side-menu li").removeClass('selected_a');
                    }
                    $(this).parent("li").addClass('selected_a');
                    $(this).parent("li").parent("ul").parent("li").addClass('selected_a active');
                    if(checkElement.is('.menu-item-child') && checkElement.is(':visible')) {
                        checkElement.slideUp(animationSpeed, function() {
                            checkElement.removeClass('menu-open');
                        });
                        checkElement.parent("li").removeClass("active");
                    }
                    //如果菜单是不可见的
                    else if((checkElement.is('.menu-item-child')) && (!checkElement.is(':visible'))) {
                        //获取上级菜单
                        var parent = liForOpen.parents('ul').first();
                        //从父级开始找所有打开的菜单并关闭
                        var ul = parent.find('ul:visible').slideUp(animationSpeed);
                        //在父级中移出menu-open标记
                        ul.removeClass('menu-open');
                        //获取父级li
                        var parent_li = liForOpen.parent("li");
                        //打开菜单时添加menu-open标记
                        checkElement.slideDown(animationSpeed, function() {
                            //添加样式active到父级li
                            checkElement.addClass('menu-open');
                            parent.find('li.active').removeClass('active');
                            parent_li.addClass('active');
                            if(liForOpen.attr("data-id")){
                                $(".active .img_right_icon").attr('src', 'common/images/arrow_down2.png');
                                $(".side-menu .active a>.img_right_icon").css('margin-top', '10px');
                            }
                        });
                    }
                }
            });
            window.parent.addIframe(liForOpen);
        })
        $(".tab-nav-content a",parent.document).each(function(i, e) {
            if(i != 0) {
                $(e).remove();
            } else {
                $(e).addClass('active');
            }
        });
        $("#layout-main-body iframe",parent.document).each(function(i, e) {
            if(i != 0) {
                $(e).remove();
            } else {
                $(e).css('display', 'block');
            }
        })


    })
}